package com.genokon.druid.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.genokon.druid.entity.GenHpoTemp;
import com.genokon.druid.service.GenHpoTempService;
import com.genokon.druid.service.HpoService;
import com.genokon.druid.service.RequestHopDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author by baichaoda
 * @date 2020/7/31 14:22
 */
@Service("HopService")
@Slf4j
public class HpoServiceImpl implements HpoService {
    @Resource
    private RequestHopDataService requestHopDataService;
    @Resource
    private GenHpoTempService genHpoTempService;
    @Override
    public String downloadDatabase(String auth) {
        ExecutorService executorService = new ThreadPoolExecutor(1, 1,
                0, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(512),
                new ThreadPoolExecutor.DiscardPolicy());
        executorService.execute(new DownLoadThread(auth));
        return "success";
    }

    public class DownLoadThread implements Runnable{
        private final String auth;
        DownLoadThread(String auth){
            this.auth = auth;
        }

        @Override
        public void run() {
            int page = 636;
            while (true){
                String rs = requestHopDataService.getHpo(this.auth, page);
                JSONObject rsObject = JSONObject.parseObject(rs);
                JSONArray results = rsObject.getJSONArray("results");

                for (int i = 0; i < results.size(); i++){
                    JSONObject object = results.getJSONObject(i);
                    GenHpoTemp tmp = new GenHpoTemp();
                    tmp.setHpoId(object.getString("hpoId"));
                    tmp.setNameEn(object.getString("name_en"));
                    tmp.setNameCn(object.getString("name_cn"));
                    tmp.setDefinitionEn(object.getString("definition_en"));
                    tmp.setDefinitionCn(object.getString("definition_cn"));
                    object.getString("category");
                    List<String> cas = handleCategory(object.getJSONArray("category"));
                    tmp.setCategory(cas.get(0));
                    tmp.setCategoryCn(cas.get(1));
                    tmp.setChildren(String.join(",", object.getJSONArray("children").toJavaList(String.class)));
                    tmp.setParent(String.join(",", object.getJSONArray("parent").toJavaList(String.class)));
                    tmp.setOmi(object.getJSONArray("omim").toJSONString().replace("http://49.4.68.254:8081/knowledge/omim/", "").replace("/", ""));

                    genHpoTempService.saveOrUpdate(tmp, new QueryWrapper<GenHpoTemp>().lambda().eq(GenHpoTemp::getHpoId, tmp.getHpoId()));
                }

                log.info("==========complete=======" + page + "=====page=========");


                if (results.size() < 20){
                    break;
                }
                page++;
            }
            log.info("==========complete=======success=========");
        }

        /**
         * 处理类目s
         * @param categories 类目s
         * @return s
         */
        public List<String> handleCategory(JSONArray categories){
            List<String> list = new ArrayList<>();
            StringBuilder caEn = new StringBuilder();
            StringBuilder caCn = new StringBuilder();
            for (int i = 0; i < categories.size(); i++){
                String ca = categories.getString(i);
                String[] str = ca.split("\\(");
                if (str.length == 2){
                    caEn.append(str[0]).append(",");
                    caCn.append(str[1].replace(")", "")).append(",");
                }else {
                    caEn.append(ca);
                }
            }
            list.add(caEn.toString());
            list.add(caCn.toString());
            return list;
        }
    }
}
